package com.cindata

import com.cindata.dictionary.*
import com.cindata.dimension.RiskDimension
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import grails.converters.JSON
import java.text.SimpleDateFormat
import org.grails.web.util.WebUtils

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class AttachmentController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond Attachment.list(params), model:[attachmentCount: Attachment.count()]
    }

    def show(Collateral collateral)
    {
        def targetUri = request.getHeader("referer")
        def attachmentTypeName = params['attachmentTypeName']
        def photoes = Attachment.findAll("from Attachment where collateral.id = ? and type.name = ? order by displayOrder, createdDate asc", [collateral?.id, attachmentTypeName])

        respond collateral, model: [attachmentTypeName: attachmentTypeName, photoes: photoes, targetUri: targetUri]
    }

    def showAccount(Account account)
    {
        def targetUri = request.getHeader("referer")
        def attachmentTypeName = params['attachmentTypeName']
        def photoes = Attachment.findAll("from Attachment where account.id = ? and type.name = ? order by displayOrder, createdDate asc", [account?.id, attachmentTypeName])

        respond account, model: [attachmentTypeName: attachmentTypeName, photoes: photoes, targetUri: targetUri], view:"attachmentShow"
    }

    def riskWarningShow(RiskWarning riskWarning)
    {
        def targetUri = request.getHeader("referer")
        def attachmentTypeName = params['attachmentTypeName']
        def photoes = Attachment.findAll("from Attachment where riskWarning.id = ? and type.name = ? order by displayOrder, createdDate asc", [riskWarning?.id, attachmentTypeName])

        respond riskWarning, model: [attachmentTypeName: attachmentTypeName, photoes: photoes, targetUri: targetUri], view:"attachmentShow"
    }

    def abnormalMortgageBatchShow(AbnormalMortgageBatch abnormalMortgageBatch)
    {
        def targetUri = request.getHeader("referer")
        def attachmentTypeName = params['attachmentTypeName']
        def photoes = Attachment.findAll("from Attachment where abnormalMortgageBatch.id = ? and type.name = ? order by displayOrder, createdDate asc", [abnormalMortgageBatch?.id, attachmentTypeName])

        respond abnormalMortgageBatch, model: [attachmentTypeName: attachmentTypeName, photoes: photoes, targetUri: targetUri], view:"attachmentShow"
    }

    // def mortgageCollectionRecordShow(MortgageCollectionRecord mortgageCollectionRecord)
    // {
    //     def targetUri = request.getHeader("referer")
    //     def photoes = Attachment.findAll("from Attachment where mortgageCollectionRecord.id = ? order by displayOrder, createdDate asc", [mortgageCollectionRecord?.id])

    //     respond mortgageCollectionRecord, model: [photoes: photoes, targetUri: targetUri], view: 'attachmentShow'
    // }

    // def mortgageLitigationRecordShow(MortgageLitigationRecord mortgageLitigationRecord)
    // {
    //     def targetUri = request.getHeader("referer")
    //     def photoes = Attachment.findAll("from Attachment where mortgageLitigationRecord.id = ? order by displayOrder, createdDate asc", [mortgageLitigationRecord?.id])

    //     respond mortgageLitigationRecord, model: [photoes: photoes, targetUri: targetUri], view: 'attachmentShow'
    // }

    def create()
    {
        def targetUri = request.getHeader("referer")
        respond new Attachment(params), model: [targetUri: targetUri]
    }

    @Transactional
    def save(Attachment attachment) {
        if (attachment == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (attachment.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond attachment.errors, view:'create'
            return
        }

        attachment.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'attachment.label', default: 'Attachment'), attachment.id])
                redirect attachment
            }
            '*' { respond attachment, [status: CREATED] }
        }
    }

    def edit(Attachment attachment) {
        respond attachment
    }

    @Transactional
    def update(Attachment attachment) {
        if (attachment == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (attachment.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond attachment.errors, view:'edit'
            return
        }

        attachment.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'attachment.label', default: 'Attachment'), attachment.id])
                redirect attachment
            }
            '*'{ respond attachment, [status: OK] }
        }
    }

    @Transactional
    def delete(Attachment attachment) {

        if (attachment == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        attachment.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'attachment.label', default: 'Attachment'), attachment.id])
                redirect uri: params['targetUri']
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'attachment.label', default: 'Attachment'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    @Secured(['permitAll'])
    @Transactional
    def uploadAvatar(Attachment attachment)
    {
        def file = request.getFile("file")
        if (file.empty)
        {
            flash.message = message(code: '请选择要上传的文件')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }
        def imageExtensionsList = ['jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG']
        def fileExtensionsList = ['pdf', 'doc', 'docx', 'xlsx', 'xls']
        def videoExtensionsList = ['mov', 'mp4', 'avi', 'rm', '3gp', 'mkv', 'wmv', 'ogg', 'rmvb']
        def audioExtensionsList = ['mp3','wav','amr','mid']
        def fileSize = request.getContentLength()
        if (fileSize > 20971520)
        {
            flash.message = message(code: '文件大小不能超过20M')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }
        def fileOrgName = file?.getOriginalFilename()
        def fileType = fileOrgName?.split('\\.')[-1]
        fileType = fileType?.toLowerCase()
        if (!(fileType in imageExtensionsList) && !(fileType in fileExtensionsList) && !(fileType in videoExtensionsList)&& !(fileType in audioExtensionsList))
        {
            flash.message = message(code: '文件格式不支持')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }

        // Company company = Company.findAll()[0]
        // String fileServer = company?.fileServer

        String fileServer = null
        def code = UUID.randomUUID().toString()
        File fileImage = new File(servletContext.getRealPath("/"), "images/${code}.${fileType}")
        file.transferTo(fileImage)

        if (fileServer)
        {
            // 上传图片信息
            def param = [:]
            param.put("fileType", fileType)
            def fileUrl = fileServerService.upload(fileImage, param, fileServer)
            def thumbnailUrl = fileServerService.compress(fileImage, param, fileServer)

            // 删除临时文件
            if (fileImage.isFile() && fileImage.exists())
            {
                def flag = fileImage.delete()
            }
            // 存储到文件服务器
            if (fileUrl)
            {
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy")
                SimpleDateFormat sdf2 = new SimpleDateFormat("MM")
                SimpleDateFormat sdf3 = new SimpleDateFormat("dd")
                Date date = new Date()

                def year = sdf1.format(date)
                def month = sdf2.format(date)
                def day = sdf3.format(date)

                attachment.fileName = fileOrgName
                attachment.fileUrl = fileServer + "/static/images/${year}/${month}/${day}/${fileUrl}.${fileType}"
                if (thumbnailUrl)
                {
                    attachment.thumbnailUrl = fileServer + "/static/images/${year}/${month}/${day}/${thumbnailUrl}.${fileType}"
                }
            }
            else
            {
                flash.message = message(code: '调用上传文件服务失败，请稍后重试')
                respond attachment, model: [targetUri: params['targetUri']], view: 'create'
                return
            }
        }
        else
        {
            attachment.fileName = fileOrgName
            attachment.fileUrl = WebUtils.retrieveGrailsWebRequest().getBaseUrl() + "/static/images/${code}.${fileType}"
        }

        attachment.description = fileOrgName?.split('\\.')[0]
        def o = [:]
        def files = []
        def sfile = [:]
        if (fileType in imageExtensionsList)
        {
            sfile['thumbnailUrl'] = attachment.fileUrl
        }
        else
        {
            sfile['thumbnailUrl'] = ''
        }
        sfile['name'] = fileOrgName
        files.add(sfile)
        o['files'] = files
        if (attachment.validate())
        {
            println "fileUrl:" + attachment.fileUrl
            attachment.save flush: true
            render o as JSON
        }
        else
        {
            flash.message = message(code: '文件上传失败，请稍后重试')
            respond attachment, model: [targetUri: params['targetUri']], view: 'create'
            return
        }
    }

    @Transactional
    def ajaxUpdate(Attachment attachment)
    {
        def description = params['description']
        attachment.description = description
        attachment.save()
        render([status: "success"] as JSON)
        return
    }
}
